package com.cghs.ac.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;

public class FileUtils {

	/**
	 * 检查路径，不存在则新建文件夹。
	 * 
	 * @param dirPath
	 *            需要检查的文件路径
	 * @return true: 文件夹存在或者已创建。false:出现异常
	 */

	public static boolean mkdirs(String dirPath) {
		File file = new File(dirPath);
		if (file.exists()) {
			if (file.isDirectory()) {
				return true;
			}
			return false;
		}
		return file.mkdirs();
	}
	
    /**
     * @brief assets路径内内容复制进目录路径
     * @param assetsPath assets路径
     * @param dirPath 目录路径
     * @param isSmart true: only when a file doesn't exist; false: override.
     * @throws IOException
     */
    public static void assetsCopy(Context c, String assetsPath, String dirPath, boolean isSmart) throws IOException {
        AssetManager am = c.getAssets();
        String[] list = am.list(assetsPath);
        if (list.length == 0) { // 文件
            File file = new File(dirPath);
            if (!isSmart || !file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
                InputStream in = am.open(assetsPath);
                FileOutputStream fout = new FileOutputStream(file);
                write(in, fout); // 复制
            }
        } else { // 目录
            for (String path : list) {
                assetsCopy(c, join(assetsPath, path), join(dirPath, path), isSmart);
            }
        }
    }
    private static String join(String prefix, String suffix) {
        int prefixLength = prefix.length();
        boolean haveSlash = (prefixLength > 0 && prefix.charAt(prefixLength - 1) == File.separatorChar);
        if (!haveSlash) {
            haveSlash = (suffix.length() > 0 && suffix.charAt(0) == File.separatorChar);
        }
        return haveSlash ? (prefix + suffix) : (prefix + File.separatorChar + suffix);
    }
 

    private static void write(InputStream in, OutputStream out) throws IOException {
        byte[] buf = new byte[1024];
        int count;
        try {
            while ((count = in.read(buf)) != -1) {
                out.write(buf, 0, count);
            }
            out.flush();
        } finally {
            in.close();
            out.close();
        }
    }
	
	/**
	 * 删除目录下 上次修改时间与当前时间 大于 keepTimeInMs 间隔时间的文件
	 * 
	 * @param path
	 *            需要遍历的目录
	 * @param keepTimeInMs
	 *            保留文件的时间， 单位:ms
	 */
	public synchronized static void deleteFiles(String path, long keepTimeInMs) {
		File dir = new File(path);
		if (dir.exists()&& dir.isDirectory()) {
			File[] files = dir.listFiles();
			for (File f : files) {
				if (System.currentTimeMillis() - f.lastModified() > keepTimeInMs) {
					f.delete();
				}
			}
		}
	}

	public static boolean checkSDCardExist() {
		boolean exist = true;
		String state = Environment.getExternalStorageState();
		if (!Environment.MEDIA_MOUNTED.equals(state)
				|| Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			exist = false;
		}
		return exist;
	}

	// public static void copyTsToSdcard(String filename) {
	// InputStream myInput;
	// OutputStream myOutput;
	// try {
	// myOutput = new FileOutputStream("/sdcard/TS/"+filename);
	// myInput = Common.context.getAssets().open(filename);
	// byte[] buffer = new byte[1024];
	// int length = myInput.read(buffer);
	// while (length > 0) {
	// myOutput.write(buffer, 0, length);
	// length = myInput.read(buffer);
	// }
	//
	// myOutput.flush();
	// myInput.close();
	// myOutput.close();
	// } catch (FileNotFoundException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// } catch (IOException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	//
	//
	// }

}
